<?php

namespace app\http\middleware;

use app\common\controller\Auth;
use app\common\controller\CommonBase;
use Firebase\JWT\JWT;
use think\Config;


class ApiAuth extends CommonBase
{

    public function handle($request, \Closure $next)
    {
        require_once "../extend/firebase/php-jwt/src/JWT.php";
        // Jwt 验证登录Bearer
        $auth1 = Auth::instance();
        $key = \Config::get('config.jwt.jwt_key');

        $jwt = substr($request->header('token'), 0);
        $member = null;

        try{
            JWT::$leeway += 15;

            $jwt = (array)JWT::decode($jwt, $key, ['HS256']);

//            if ($jwt && $jwt['exp'] > time()){
//                $member = $auth->user($jwt);
//            }

            if ($jwt){
                $member = $auth1->user($jwt);
            }
        }catch (\Exception $e){

            $jwt = null;
        }

        app()->auth = $auth1;
        app()->member = $member;

        //检查访问权限
        if (!$auth1->checkPublicUrl()){
            if (empty($jwt)){
                $this->fail1('登录已过期请重新登录');
            }

            if (!$member){
                $this->fail1('登录已过期，请重新登录');
            }
            if ($member['token'] != $jwt['token']){
                $this->fail1('用户验证失败，请重新登录');
            }
        }

        return $next($request);
    }
}
